package com.xindacloud.sms.console.system.controller;


import com.xindacloud.sms.console.constant.SessionKeys;
import com.xindacloud.sms.console.result.Result;
import com.xindacloud.sms.console.result.ResultGenerator;
import com.xindacloud.sms.console.system.dto.ProjectMemberDTO;
import com.xindacloud.sms.console.system.dto.QueryProjectListDTO;
import com.xindacloud.sms.console.system.dto.SaveSmsProjectDTO;
import com.xindacloud.sms.console.system.entity.SmsProject;
import com.xindacloud.sms.console.system.entity.SmsProjectMember;
import com.xindacloud.sms.console.system.entity.SmsUser;
import com.xindacloud.sms.console.system.service.ISmsProjectMemberService;
import com.xindacloud.sms.console.system.service.ISmsProjectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 短信项目 前端控制器
 * </p>
 *
 * @author czc
 * @since 2019-10-08
 */
@Api(tags = {"项目管理模块"})
@Slf4j
@RestController
@RequestMapping("/api/v1/sms-project")
public class SmsProjectController {

    private final ISmsProjectService smsProjectService;

    private final ISmsProjectMemberService smsProjectMemberService;

    @Autowired
    public SmsProjectController(ISmsProjectService smsProjectService,
                                ISmsProjectMemberService smsProjectMemberService) {
        this.smsProjectService = smsProjectService;
        this.smsProjectMemberService = smsProjectMemberService;
    }

    @ApiOperation(value = "获取项目列表", response = SmsProject.class, notes = "[已联调完毕]")
    @PostMapping(value = "/getSmsProjectList")
    public Result getSmsProjectList(@ApiParam(name = "queryProjectListDTO", value = "查询项目列表DTO", required = true)
                                    @RequestBody QueryProjectListDTO queryProjectListDTO,HttpServletRequest request) {
    	 SmsUser smsUser = (SmsUser) request.getSession().getAttribute(SessionKeys.ACCOUNT);
    	 queryProjectListDTO.setCreateUserId(smsUser.getUserId());
        return smsProjectService.getSmsProjectList(queryProjectListDTO);
    }

    @ApiOperation(value = "修改项目", response = Result.class, notes = "该接口code返回200为成功其他均为失败,[已联调完毕]")
    @PutMapping(value = "/modify")
    public Result modifyProject(@ApiParam(name = "updateProjectDTO", value = "更新项目对象DTO", required = true)
                                @RequestBody SaveSmsProjectDTO updateProjectDTO) {

        final SmsProject smsProject = smsProjectService.updateSmsProject(updateProjectDTO);
        if (Objects.isNull(smsProject)) {
            return ResultGenerator.genClientFailResult("修改项目失败");
        }

        if (CollectionUtils.isNotEmpty(updateProjectDTO.getProjectMembersList())) {
            final List<SmsProjectMember> collect = updateProjectDTO.getProjectMembersList()
                    .stream()
                    .map(rs -> {
                        SmsProjectMember projectMember = new SmsProjectMember();
                        BeanUtils.copyProperties(rs, projectMember);
                        projectMember.setProjectId(updateProjectDTO.getProjectId());
                        return projectMember;
                    })
                    .collect(Collectors.toList());
            smsProjectMemberService.updateSmsProjectMember(collect);
        } else {
            smsProjectMemberService.delSmsProjectMemberByProjectId(updateProjectDTO.getProjectId());
        }
        return ResultGenerator.genSuccessResult("修改成功");
    }


    @ApiOperation(value = "添加项目", response = SmsUser.class, notes = "该接口code返回200为成功其他均为失败,[已联调完毕]")
    @PostMapping(value = "/save")
    public Result createSmsProject(@ApiParam(name = "saveSmsProjectDTO", value = "添加项目对象DTO", required = true)
                                   @RequestBody SaveSmsProjectDTO saveSmsProjectDTO,
                                   HttpServletRequest request) {

        SmsUser smsUser = (SmsUser) request.getSession(false).getAttribute(SessionKeys.ACCOUNT);
        saveSmsProjectDTO.setCreateUserId(smsUser.getUserId());
        saveSmsProjectDTO.setProjectId(null);
        final SmsProject smsProject = smsProjectService.querySmsProjectInfo(saveSmsProjectDTO.getSmsProjectName(),
                saveSmsProjectDTO.getToken(), saveSmsProjectDTO.getPassword());
        if (Objects.nonNull(smsProject)) {
            return ResultGenerator.genClientFailResult("项目名称,token,password不能重复.");
        }
        SmsProject smsProjectResult = smsProjectService.saveSmsProject(saveSmsProjectDTO);
        if (Objects.isNull(smsProjectResult)) {
            return ResultGenerator.genClientFailResult("添加项目失败");
        }
        final List<ProjectMemberDTO> projectMembersList = saveSmsProjectDTO.getProjectMembersList();
        final ProjectMemberDTO defaultMember = ProjectMemberDTO.builder()
                .userId(smsUser.getUserId())
                .username(smsUser.getUsername())
                .build();
        projectMembersList.add(defaultMember);
        final List<SmsProjectMember> projectMemberList = projectMembersList
                .stream()
                .map(rs -> SmsProjectMember.builder()
                        .projectId(Objects.requireNonNull(smsProjectResult).getProjectId())
                        .userId(rs.getUserId())
                        .build())
                .collect(Collectors.toList());
        smsProjectMemberService.saveSmsProjectMember(projectMemberList);
        return ResultGenerator.genSuccessResult(smsProjectResult);
    }

    @ApiOperation(value = "根据项目ID删除项目", notes = "该接口code返回200为成功其他均为失败,[已联调完毕]")
    @DeleteMapping(value = "/projectIds/{projectId}")
    public Result deleteSmsProject(@ApiParam(name = "projectId", value = "项目ID", required = true)
                                   @PathVariable(name = "projectId", value = "projectId") String projectId) {
        smsProjectMemberService.delSmsProjectMemberByProjectId(projectId);
        smsProjectService.deleteSmsProject(projectId);
        return ResultGenerator.genSuccessResult("删除成功");
    }

}
